import requests
import pandas as pd

# 1. 准备数据
data = {
    "Date": ["2025-01-01", "2025-01-02", "2025-01-03"],
    "Revenue": [5000, 7000, 6000],
    "Product": ["A", "B", "A"]
}
df = pd.DataFrame(data)
df.to_csv("sales_data.csv", index=False)

# 2. 调用API
# 从 "D:\Documents\deepseek_key.txt"加载api_key
def load_api_key():
    try:
        with open("D:\\Documents\\deepseek_key.txt", "r") as f:
            return f.read().strip()
    except FileNotFoundError:
        print("警告：未找到 API key 文件，请确保文件存在于 D:\\Documents\\deepseek_key.txt")
        return ""

api_key = load_api_key()
url = "https://api.deepseek.com/v1/chat/completions"  # 修正路径

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

payload = {
    "model": "deepseek-chat",
    "messages": [
        {"role": "user", "content": "分析sales_data.csv中的收入趋势并生成HTML报告"}
    ],
    "output_format": "html"
}

try:
    response = requests.post(
    url, 
    headers=headers, 
    json=payload, 
    timeout=(10, 60)  # 连接超时10秒，读取超时30秒
    )
    response.raise_for_status()
    report = response.json().get("choices", [{}])[0].get("message", {}).get("content")
    if report:
        with open("sales_report.html", "w") as f:
            f.write(report)
        print("报告生成成功！")
    else:
        print("错误: 响应中未包含报告内容")
except Exception as e:
    print(f"请求失败: {e}\n响应详情: {response.text if 'response' in locals() else '无响应'}")
